//
//  UserAccount.swift
//  微博
//
//  Created by admin on 2018/3/23.
//  Copyright © 2018年 xm. All rights reserved.
//

import UIKit

private let saveFileName="useraccount.json"

class UserAccount: NSObject {

    ///用户授权的唯一票据
    var access_token: String?
    ///授权用户的UID
    var uid: String?
    //token效期时长，单位秒数
    //开发者 5年,每次登录之后，都是5年
    //使用者 3天,会从第一次登录递减
    var expires_in : TimeInterval=0{
        didSet {
            expires_Date = Date(timeIntervalSinceNow: expires_in)
        }
    }
    ///用户昵称
    var screen_name: String?
    ///用户头像
    var avatar_large:String?
    ///token过期日期时间
    var expires_Date: Date?
    
    override var description: String {
        return yy_modelDescription()
    }
    
    override init() {
        super.init()
        //对象初始化时就，尝试从本地恢复账户数据
        recoverAccount()
    }
    
    /// 保存账户模型到本地
    func saveAccount(){
        var dict = self.yy_modelToJSONObject() as? [String: AnyObject] ?? [:]
        dict.removeValue(forKey: "expires_in")//不需要保存，已转换为日期了
        guard let data = try?JSONSerialization.data(withJSONObject: dict, options: []),
              let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first,
              let savepath:String = (docDir as NSString).appendingPathComponent(saveFileName)
            else{
                return
        }
        (data as NSData).write(toFile: savepath, atomically: true)//写入本地
    }
    
    func recoverAccount() {
        //尝试从本地恢复数据
        guard let docDir = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first,
            let savepath:String = (docDir as NSString).appendingPathComponent(saveFileName),
            let data = NSData(contentsOfFile: savepath),
            let dict = try?JSONSerialization.jsonObject(with: data as Data, options: []) as? [String: AnyObject] ?? [:]
            else{
                return
        }
        yy_modelSet(with: dict)
        //判断token是否过期了
        if expires_Date?.compare(Date()) != .orderedDescending {
            print("账户过期了")
            access_token=nil
            uid=nil
            try?FileManager.default.removeItem(atPath: savepath)//删除过期文件信息
        }
    }
}
